#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2020/11/04
# @Author    :breeze
# @Email     :wangbaoshan@bbdservice.com
# @File      :R33_EC_PaidBusinessBadCheck
# @Software  :PyCharm

'''eof
name:申请企业已结清信贷业务为资产处置、垫款汇总笔数校验
code:R35_EC_PaidCreditInformationSummaryCntCheck_2D
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', []]


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """

    return_data = None
    data_value = str(data_value)
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d')
                    except:
                        return_data = None

    return return_data


def get_current_time():
    try:
        if cQexecuteTime is not None:
            return convertDataType(cQexecuteTime, "date_time")
        else:
            return datetime.datetime.now()
    except:
        return datetime.datetime.now()


def get_five_year_ago(curr_date):
    if curr_date is None:
        return (get_current_time() - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m%d")
    else:
        return (convertDataType(curr_date, "date_time") - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m%d")


def get_report_date():
    data = EC_DSJ_2D['data']
    # 报告头EAA [1..1]
    EAA = getTable(data, "EAA", 1, 1)
    if EAA == [{}]:
        return None
    elif EAA == 0:
        return 0
    else:
        # 报告头信息单元EA01 [1..1]
        EA01 = getTable(EAA[0], "EA01", 1, 1)
        if EA01 == [{}]:
            return None
        elif EA01 == 0:
            return 0
        else:
            # 报告标识信息段 EA01A [1..1]
            EA01A = getTable(EA01[0], "EA01A", 1, 1)
            if EA01 == [{}]:
                return None
            elif EA01 == 0:
                return 0
            else:
                EA01AR01 = EA01A[0].get('EA01AR01')
                try:
                    return get_five_year_ago(EA01AR01[:10])
                except:
                    return None

def get_report_now():
    data = EC_DSJ_2D['data']
    # 报告头EAA [1..1]
    EAA = getTable(data, "EAA", 1, 1)
    if EAA == [{}]:
        return None
    elif EAA == 0:
        return 0
    else:
        # 报告头信息单元EA01 [1..1]
        EA01 = getTable(EAA[0], "EA01", 1, 1)
        if EA01 == [{}]:
            return None
        elif EA01 == 0:
            return 0
        else:
            # 报告标识信息段 EA01A [1..1]
            EA01A = getTable(EA01[0], "EA01A", 1, 1)
            if EA01 == [{}]:
                return None
            elif EA01 == 0:
                return 0
            else:
                EA01AR01 = EA01A[0].get('EA01AR01')
                return EA01AR01

def factor3(five_years_ago):
    data = EC_DSJ_2D['data']
    # 担保账户信息   [1..1]
    EDB = getTable(data, "EDB", 1, 0)
    if EDB == [{}]:
        return None
    elif EDB == 0:
        return 0
    else:
        # 担保账户信息明细单元   [0..*]
        ED04 = getTable(EDB[0], "ED04", 0, 1)
        if ED04 == [{}]:
            return None
        elif ED04 == 0:
            return 0
        else:
            factor_list = []
            for i in ED04:
                try:
                    # 在保责任信息段   [1..1]
                    ED04B = getTable(i, 'ED04B', 1, 1)
                    # 基本信息段   [1..1]
                    ED04A = getTable(i, 'ED04A', 1, 1)
                    if ED04A == [{}] or ED04B == [{}]:
                        factor_list.append(None)
                    elif ED04A == 0 or ED04B == 0:
                        factor_list.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED04BD01 = ED04B[0].get('ED04BD01')
                        # 代偿（垫款）标志    [1..1]
                        ED04BD03 = ED04B[0].get('ED04BD03')
                        # 关闭日期   [1..1]
                        ED04BR02 = ED04B[0].get('ED04BR02')
                        # 到期日期
                        ED04AR02 = ED04A[0].get('ED04AR02')
                        if ED04BD01 in null_type_list or ED04BD03 in null_type_list:
                            factor_list.append(None)
                        else:
                            ED04AR02 = convertDataType(ED04AR02, "date_time")
                            if ED04BD01 == "2" and ED04BD03 == "1":
                                if ED04BR02 in null_type_list:
                                    if ED04AR02 in null_type_list or five_years_ago is None or five_years_ago == 0:
                                        factor_list.append(1)
                                    elif five_years_ago < ED04AR02.strftime("%Y%m%d") <= convertDataType(get_report_now()[:10], "date_time").strftime("%Y%m%d"):
                                        factor_list.append(1)
                                    else:
                                        factor_list.append(0)
                                elif ED04BR02 not in null_type_list:
                                    ED04BR02 = convertDataType(ED04BR02, "date_time")
                                    if five_years_ago is None or five_years_ago == 0:
                                        factor_list.append(1)
                                    elif ED04BR02 not in null_type_list:
                                        if five_years_ago < ED04BR02.strftime("%Y%m%d") <= convertDataType(get_report_now()[:10], "date_time").strftime("%Y%m%d"):
                                            factor_list.append(1)
                                        else:
                                            factor_list.append(0)
                                    else:
                                        factor_list.append(0)
                                else:
                                    factor_list.append(0)
                            else:
                                factor_list.append(0)
                except:
                    factor_list.append(None)
                    continue
            factor = filter(lambda x: x is not None, factor_list)
            if len(factor) == 0:
                return None
            else:
                return sum(factor)


def factor4(five_years_ago):
    data = EC_DSJ_2D['data']
    # 借贷账户信息   [1..1]
    EDA = getTable(data, "EDA", 1, 0)
    if EDA == [{}]:
        return None
    elif EDA == 0:
        return 0
    else:
        # 借贷账户信息单元   [0..*]
        ED01 = getTable(EDA[0], "ED01", 0, 1)
        if ED01 == [{}]:
            return None
        elif ED01 == 0:
            return 0
        else:
            factor_list = []
            for i in ED01:
                try:
                    # 基本信息段   [1..1]
                    ED01A = getTable(i, 'ED01A', 1, 1)
                    if ED01A == [{}]:
                        factor_list.append(None)
                    elif ED01A == 0:
                        factor_list.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED01AD01 = ED01A[0].get('ED01AD01')
                        # 借贷账户类型    [1..1]
                        ED01AD02 = ED01A[0].get('ED01AD02')
                        # 借贷业务种类大类   [1..1]
                        ED01AD05 = ED01A[0].get('ED01AD05')
                        # 关闭日期   [1..1]
                        ED01AR03 = ED01A[0].get('ED01AR03')
                        # 到期日期 [1..1]
                        ED01AR02 = ED01A[0].get('ED01AR02')

                        if ED01AD01 in null_type_list or ED01AD02 in null_type_list or \
                                ED01AD05 in null_type_list:
                            factor_list.append(None)
                        else:
                            ED01AR02 = convertDataType(ED01AR02, "date_time")
                            if ED01AD01 == "2" and ED01AD02 in ("D1", "D2", "R1", "R4", "C1") and ED01AD05 in ("41", "51"):
                                if ED01AR03 in null_type_list:
                                    if ED01AR02 in null_type_list or five_years_ago is None or five_years_ago == 0:
                                        factor_list.append(1)
                                    elif five_years_ago < ED01AR02.strftime("%Y%m%d") <= convertDataType(get_report_now()[:10], "date_time").strftime("%Y%m%d"):
                                        factor_list.append(1)
                                    else:
                                        factor_list.append(0)
                                elif ED01AR03 not in null_type_list:
                                    ED01AR03 = convertDataType(ED01AR03, "date_time")
                                    if five_years_ago is None or five_years_ago == 0:
                                        factor_list.append(1)
                                    elif ED01AR03 not in null_type_list:
                                        if five_years_ago < ED01AR03.strftime("%Y%m%d") <= convertDataType(get_report_now()[:10], "date_time").strftime("%Y%m%d"):
                                            factor_list.append(1)
                                        else:
                                            factor_list.append(0)
                                    else:
                                        factor_list.append(0)
                                else:
                                    factor_list.append(0)
                            else:
                                factor_list.append(0)
                except:
                    factor_list.append(None)
                    continue
            factor = filter(lambda x: x is not None, factor_list)
            if len(factor) == 0:
                return None
            else:
                return sum(factor)


def factor5(five_years_ago):
    data = EC_DSJ_2D['data']
    # 借贷账户信息   [1..1]
    EDA = getTable(data, "EDA", 1, 0)
    if EDA == [{}]:
        return None
    elif EDA == 0:
        return 0
    else:
        # 借贷账户信息单元   [0..*]
        ED01 = getTable(EDA[0], "ED01", 0, 1)
        if ED01 == [{}]:
            return None
        elif ED01 == 0:
            return 0
        else:
            factor_list = []
            for i in ED01:
                try:
                    # 基本信息段   [1..1]
                    ED01A = getTable(i, 'ED01A', 1, 1)
                    # 还款信息段   [1..1]
                    ED01B = getTable(i, 'ED01B', 1, 1)
                    if ED01A == [{}] or ED01B == [{}]:
                        factor_list.append(None)
                    elif ED01A == 0 or ED01B == 0:
                        factor_list.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED01AD01 = ED01A[0].get('ED01AD01')
                        # 借贷账户类型    [1..1]
                        ED01AD02 = ED01A[0].get('ED01AD02')
                        # 关闭日期   [1..1]
                        ED01AR03 = ED01A[0].get('ED01AR03')
                        # 到期日期 [1..1]
                        ED01AR02 = ED01A[0].get('ED01AR02')
                        # 还款表现信息 [0..*]
                        ED01BH = getTable(ED01B[0], 'ED01BH', 0, 1)
                        last_five_class = None
                        if ED01BH == [{}]:
                            factor_list.append(None)
                        elif ED01BH == 0:
                            factor_list.append(None)
                        else:
                            max_date = None
                            for j in ED01BH:
                                # 最近一次还款形式   [1..1]
                                ED01BD02 = j.get('ED01BD02')
                                # 信息报告日期   [1..1]
                                ED01BR01 = convertDataType(j.get('ED01BR01'), "date_time")
                                if ED01BR01 is not None and ED01BD02 is not None:
                                    if max_date is None:
                                        max_date = ED01BR01
                                        last_five_class = ED01BD02
                                    elif ED01BR01 > max_date:
                                        max_date = ED01BR01
                                        last_five_class = ED01BD02

                        if ED01AD01 in null_type_list or ED01AD02 in null_type_list or last_five_class in null_type_list:
                            factor_list.append(None)
                        else:
                            ED01AR02 = convertDataType(ED01AR02, "date_time")
                            if ED01AD01 in ("2") and ED01AD02 in ("D1", "D2", "R1", "R4", "C1") and \
                                    last_five_class in ("21", "43", "51", "31", "32", "41", "42", "52", "61", "62", "63"):
                                if ED01AR03 in null_type_list:
                                    if ED01AR02 in null_type_list or five_years_ago is None or five_years_ago == 0:
                                        factor_list.append(1)
                                    elif five_years_ago < ED01AR02.strftime("%Y%m%d") <= convertDataType(get_report_now()[:10], "date_time").strftime("%Y%m%d"):
                                        factor_list.append(1)
                                    else:
                                        factor_list.append(0)
                                elif ED01AR03 not in null_type_list:
                                    ED01AR03 = convertDataType(ED01AR03, "date_time")
                                    if five_years_ago is None or five_years_ago == 0:
                                        factor_list.append(1)
                                    elif ED01AR03 not in null_type_list:
                                        if five_years_ago < ED01AR03.strftime("%Y%m%d") <= convertDataType(get_report_now()[:10], "date_time").strftime("%Y%m%d"):
                                            factor_list.append(1)
                                        else:
                                            factor_list.append(0)
                                    else:
                                        factor_list.append(0)
                                else:
                                    factor_list.append(0)
                            else:
                                factor_list.append(0)
                except:
                    factor_list.append(None)
                    continue
            factor = filter(lambda x: x is not None, factor_list)
            if len(factor) == 0:
                return None
            else:
                return sum(factor)


def factor6(five_years_ago):
    data = EC_DSJ_2D['data']
    # 借贷账户信息   [1..1]
    EDB = getTable(data, "EDB", 1, 0)
    if EDB == [{}]:
        return None
    elif EDB == 0:
        return 0
    else:
        # 担保账户信息明细单元   [0..*]
        ED04 = getTable(EDB[0], "ED04", 0, 1)
        if ED04 == [{}]:
            return None
        elif ED04 == 0:
            return 0
        else:
            factor_list = []
            for i in ED04:
                try:
                    # 在保责任信息段   [1..1]
                    ED04B = getTable(i, 'ED04B', 1, 1)
                    # 基本信息段   [1..1]
                    ED04A = getTable(i, 'ED04A', 1, 1)
                    if ED04A == [{}] or ED04B == [{}]:
                        factor_list.append(None)
                    elif ED04A == 0 or ED04B == 0:
                        factor_list.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED04BD01 = ED04B[0].get('ED04BD01')
                        # 代偿（垫款）标志   [1..1]
                        ED04BD03 = ED04B[0].get('ED04BD03')
                        # 余额   [1..1]
                        ED04BJ01 = ED04B[0].get('ED04BJ01')
                        # 关闭日期   [1..1]
                        ED04BR02 = ED04B[0].get('ED04BR02')
                        # 担保交易业务种类细分   [1..1]
                        ED04AD03 = ED04A[0].get('ED04AD03')
                        # 到期日期
                        ED04AR02 = ED04A[0].get('ED04AR02')

                        if ED04BD01 in null_type_list or ED04BD03 in null_type_list or \
                                isFloat(ED04BJ01) in null_type_list or ED04AD03 in null_type_list:
                            factor_list.append(None)
                        else:
                            ED04AR02 = convertDataType(ED04AR02, "date_time")
                            if ED04BD01 == "2" and float(ED04BJ01) == 0 and ED04AD03 in ("61", "05", "71", "72") and ED04BD03 == "1":
                                if ED04BR02 in null_type_list:
                                    if ED04AR02 in null_type_list or five_years_ago is None or five_years_ago == 0:
                                        factor_list.append(1)
                                    elif five_years_ago < ED04AR02.strftime("%Y%m%d") <= convertDataType(get_report_now()[:10], "date_time").strftime("%Y%m%d"):
                                        factor_list.append(1)
                                    else:
                                        factor_list.append(0)
                                elif ED04BR02 not in null_type_list:
                                    ED04BR02 = convertDataType(ED04BR02, "date_time")
                                    if five_years_ago is None or five_years_ago == 0:
                                        factor_list.append(1)
                                    elif ED04BR02 not in null_type_list:
                                        if five_years_ago < ED04BR02.strftime("%Y%m%d") <= convertDataType(get_report_now()[:10], "date_time").strftime("%Y%m%d"):
                                            factor_list.append(1)
                                        else:
                                            factor_list.append(0)
                                    else:
                                        factor_list.append(0)
                                else:
                                    factor_list.append(0)
                            else:
                                factor_list.append(0)
                except:
                    factor_list.append(None)
                    continue
            factor = filter(lambda x: x is not None, factor_list)
            if len(factor) == 0:
                return None
            else:
                return sum(factor)


def R35_EC_PaidCreditInformationSummaryCntCheck():
    """
    Factor3=统计担保账户信息单元·在保责任信息段(ED04B)·账户活动状态(ED04BD01)==2(已结清)and代偿（垫款）标志(ED04BD03)==1(是)的笔数；
    if关闭日期（ED01BR02）不为空，则取在60个月内的笔数，if关闭日期（ED01BR02）为空或缺失，则不做时间限制的条件判断。
    Factor4=统计借贷账户信息单元·基本信息段(ED01A)·账户活动状态(ED01AD01)==2(已结清) and 借贷账户类型(ED01AD02) ∈(D1(非循环贷账户),D2(贴现账户),R1(循环贷账户),R4(循环额度下分账户),C1(催收账户)) and 借贷业务种类大类(ED01AD05)∈(41(垫款),51(资产处置))的笔数；
    if关闭日期（ED01AR03）不为空，则取在60个月内的笔数，if关闭日期（ED01AR03）为空或缺失，则不做时间限制的条件判断。
    Factor5=统计借贷账户信息单元下·基本信息段(ED01A)·账户活动状态(ED01AD01)==2（已结清）and 借贷账户类型(ED01AD02) ∈(D1(非循环贷账户),D2(贴现账户),R1(循环贷账户),R4(循环额度下分账户),C1(催收账户))&还款表现信息段（ED01B）·最近一次还款形式（ED01BD02）∈(21(担保代偿),43(资产剥离),51(债转股),31(资产重组),32(减免),41(债权转让),42(债券置换),52(以资抵债),61(诉讼追偿),62(破产清偿),63(委托处置))的笔数；
    if关闭日期（ED01AR03）不为空，则取在60个月内的笔数，if关闭日期（ED01AR03）为空或缺失，则不做时间限制的条件判断。
    Factor6=统计担保账户信息-担保账户信息明细单元（ED04）-在保责任信息段（ED04B）-账户活动状态（ED04BD01）=2(已结清）、and基本信息段（ED04A）-担保交易业务种类细分（ED04AD03）∈（61（银行承兑汇票）、71（融资类银行保函）、72（非融资类银行保函））and 余额 （ED04BJ01）=0 and 垫款标志(ED04BD03)==1(是)的笔数，
    if关闭日期（ED04BR02）不为空，则取在60个月内的笔数，if关闭日期（ED04BR02）为空或缺失，则不做时间限制的条件判断。
    Factor=MAX(Factor1,Factor2,Factor3,Factor4,Factor5,Factor6)
    注：企业征信内所有策略数据最长取值为5年，5年定义为报告日期当月（含）往前推60个月
    :return:
    """
    five_years_ago = get_report_date()

    Factor3 = factor3(five_years_ago)
    Factor4 = factor4(five_years_ago)
    Factor5 = factor5(five_years_ago)
    Factor6 = factor6(five_years_ago)

    if Factor3 is None and Factor4 is None and Factor5 is None and Factor6 is None:
        return u'缺失值'
    else:
        Factor3 = Factor3 if Factor3 is not None else 0
        Factor4 = Factor4 if Factor4 is not None else 0
        Factor5 = Factor5 if Factor5 is not None else 0
        Factor6 = Factor6 if Factor6 is not None else 0
        Factor = max(Factor6, Factor5, Factor4, Factor3)

        return Factor


if __name__ == '__main__':
    file_obj = open(r'C:\Users\john\Desktop\samples\case(8).json', 'r')
    content = file_obj.read()
    cQexecuteTime = ""
    EC_DSJ_2D = json.loads(content, strict=False)
    aa = R35_EC_PaidCreditInformationSummaryCntCheck()
    print aa

result = R35_EC_PaidCreditInformationSummaryCntCheck()
